package com.itheima.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.SetmealService;
import com.itheima.contant.MessageConstant;
import com.itheima.contant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    /*上传图片*/
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        //1、获取图片名称

        String originalFilename = imgFile.getOriginalFilename();

        //获取文件后缀，包含 .
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);

        //上传七牛云的话，是以文件名作为唯一标识的，文件名相同则不予存储
        //所以我们要生成随机不重复的文件名
        String fileName = UUID.randomUUID() + suffix;

        try {
            //2、上传七牛云
            QiniuUtil.upload(imgFile,fileName);

            //3、将图片名返回给前端
            Result result = Result.success(MessageConstant.PIC_UPLOAD_SUCCESS);
            result.setData(fileName);

            //将图片名称保存在redis数据库中  这是上传的图片的名称
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success(MessageConstant.PIC_UPLOAD_FAIL);
        }

    }

    //分页查询
    @RequestMapping("/pageQuery")
    public PageResult pageQuery(@RequestBody QueryPageBean page){
        return setmealService.pageQuery(page.getCurrentPage(),page.getPageSize(),page.getQueryString());
    }

    //添加套餐
    @RequestMapping("/addSetmeal")
    public Result addSetmeal(@RequestBody Setmeal setmeal){

        try {
            setmealService.addSetmeal(setmeal);
            //将图片名称保存在redis数据库中  这是上传的图片的名称
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

            return Result.success(MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            return Result.error(MessageConstant.ADD_SETMEAL_FAIL);
        }
    }
}
